import React, { useState } from "react"
import styles from './Form.module.scss'

type StatusOptions = 'submitting' | 'typing' | 'success'

export default function Form() {
    const [answer, setAnswer] = useState<string>('')
    const [error, setError] = useState<Error | null>(null)
    const [status, setStatus] = useState<StatusOptions>('typing')

    if (status === 'success') {
        return <h1>答对了！</h1>
    }

    async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
        e.preventDefault()
        setStatus('submitting')
        try {
            await submitForm(answer)
            setStatus('success')
        } catch (err: any) {
            setStatus('typing')
            setError(err)
        }
    }

    function handleTextareaChange(e: React.ChangeEvent<HTMLTextAreaElement>) {
        setAnswer(e.target.value)
    }

    return (
        <>
            <h2>状态管理: 城市检测</h2>
            <p>哪个城市有把空气变成饮用水的广告牌？</p>
            <form onSubmit={handleSubmit}>
                <textarea
                    value={answer}
                    onChange={handleTextareaChange}
                    disabled={status === 'submitting'}
                />
                <br />
                <button disabled={answer.length === 0 || status === 'submitting'}>提交</button>
                {error !== null && <p className={styles.Error}>{error.message}</p>}
            </form>

        </>
    )
}

function submitForm(answer: string) {
    return new Promise<void>((resolve, reject) => {
        setTimeout(() => {
            let shouldError = answer.toLowerCase() !== 'lima'
            if (shouldError) {
                reject(new Error('猜的不错，但答案不对。再试试吧！'))
            } else {
                resolve()
            }
        }, 1500);
    })
}